package com.admin.web.config.RabbitMQ;

import com.admin.web.config.websocket.WebSocket;
import com.alibaba.fastjson.JSONObject;
import com.util.Respons.TestSocketBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 张子艺
 * @packge com.admin.config.websocket
 * @data 2019-01-16 15:27
 * @project currencycloud
 */
@Component
public class RabbitMqReceiver {
    private static Lock lock = new ReentrantLock();
    private final Logger logger = LoggerFactory.getLogger(RabbitMqReceiver.class);

    @RabbitListener(queues = "socketDataOne")
    public void data(TestSocketBean testSocketBean) {
        JSONObject json = new JSONObject();
        switch (testSocketBean.getType()) {
            case 2:
                logger.info("本次交易模拟数据为:" + testSocketBean.getData());
                json.put("msg", "本次交易模拟数据为:" + testSocketBean.getData());
                json.put("data", testSocketBean.getData());
                sendSocket(json.toJSONString());
                break;
            case 1:
                logger.info("已产生一笔交易，本次交易模拟金额为：￥ " + testSocketBean.getMoeny());
                json.put("msg", "已产生一笔交易，本次交易模拟金额为：￥ " + testSocketBean.getMoeny());
                json.put("moeny", testSocketBean.getMoeny());
                sendSocket(json.toJSONString());
                break;
            case 3:
                logger.info("结束通道: " + testSocketBean.getEnd());
                json.put("msg", testSocketBean.getEnd());
                json.put("moeny", null);
                sendSocket(json.toJSONString());
                break;
        }
    }

    public void sendSocket(String msg) {
        //群发消息
        for (WebSocket item : WebSocket.webSocketSet) {
            try {
                lock.lock();
                item.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
